#include "activityoutputrule.h"

#include "../documents/data/graphicdata.h"
#include "../documents/swpprocessdocument.h"
#include "../editors/items/graphicitemcommon.h"
#include "../utils/modelvalidator.h"

#include <gdmodelquerymaker.h>
#include <ieditoritem.h>

#include <QtGui/QAction>

using namespace core;
using namespace swp;

ActivityOutputRule::ActivityOutputRule() : QObject(0), IValidatorRule(),
    m_action(0),
    m_lastData(0),
    m_notPassed()
{
    m_action = new QAction("", this);

    connect(m_action, SIGNAL(triggered()),
        this, SLOT(selectNotPassedItems()));
}

ActivityOutputRule::~ActivityOutputRule()
{

}

bool ActivityOutputRule::isProjectWide() const
{
    return false;
}

bool ActivityOutputRule::validate(
    const QSharedPointer<IContainerDocument>& document,
    QAction*& reportClickAction, QString& reportText) const
{
    return false;
}

bool ActivityOutputRule::validate(const QSharedPointer<IDocument>& document,
    QAction*& reportClickAction, QString& reportText) const
{
    bool ret = true;

    GraphicData* data = dynamic_cast<GraphicData* >(document->data());

    Q_ASSERT(data != 0); // GraphicData expected

    m_lastData = data;
    m_notPassed.clear();

    reportClickAction = m_action;

    GDModelQueryMaker queryMaker(*data);

    const QList<IGraphicEditorItem* > activities =
        queryMaker.getItems(SWP_ACTIVITY_ITEM);


    foreach (IGraphicEditorItem* activity, activities)
    {
        if (activity->propertyValue("output").toList().first() ==
            QObject::tr("none"))
        {
            m_notPassed.append(activity);

            ret = false;
        }
    }

    reportText = QObject::tr("Every Activity should have an Output assigned");

    return ret;
}

// private slots
void ActivityOutputRule::selectNotPassedItems()
{
    if (m_lastData != 0)
    {
        ModelValidator::getInstance()->actionAboutToTrigger(m_action);

        m_lastData->clearSelection();

        foreach (IGraphicEditorItem* item, m_notPassed)
        {
            QGraphicsItem* _item  = dynamic_cast<QGraphicsItem* >(item);

            Q_ASSERT(_item != 0); // shouldn't happen

            _item->setSelected(true);
        }
    }
}
